package com.my.service.impl;

import java.util.Date;
import java.util.List;

import com.my.commons.SessionUtils;
import com.my.commons.time.DateFormat;
import com.my.dao.IBaseDao;
import com.my.entity.UserInfoEntity;
import com.my.service.IUserInfoService;

public class UserInfoService implements IUserInfoService {
	private IBaseDao baseDao;
	
	/**
	 * 添加用户
	 */
	public int addUserInfo(UserInfoEntity userInfo,String code) {
		String registerCode = (String) SessionUtils.getValue(SessionUtils.REGISTER_CODE_KEY);
		
		if(registerCode.equalsIgnoreCase(code)){
			List userInfoList = baseDao.findByValue(UserInfoEntity.class, "username", userInfo.getUsername());
			if(userInfoList.size() > 0){
				return -1;
			}
			userInfo.setCreateDate(DateFormat.formatYMDH24MS(new Date()));
			baseDao.saveEntity(userInfo);
			return 1;
		}
		return -2;
	}
	
	/**
	 * 根据字段名和值查询
	 */
	public UserInfoEntity getUserInfoByValue(String title,String value) {
		List<UserInfoEntity> userInfoList = baseDao.findByValue(UserInfoEntity.class, title, value);
		if(userInfoList.size() > 0){
			return userInfoList.get(0);
		}
		return null;
	}
	/**
	 * 用户登录
	 */
	public UserInfoEntity login(String username,String password){
		UserInfoEntity userInfo = getUserInfoByValue("username", username.trim());
		if(userInfo == null){
			return null;
		}
		if(userInfo.getPassword().equals(password)){
			return userInfo;
		}
		return null;
	}
	/**
	 * 用户找回密码
	 */
	public int retrievePass(String username,String question,String myResult){
		UserInfoEntity userInfo = getUserInfoByValue("username", username);
		if(userInfo == null){
			return -1;
		}
		if(!userInfo.getQuestion().equals(question)){
			return -2;
		}
		if(!userInfo.getReply().equals(myResult)){
			return -3;
		}
		userInfo.setPassword("123456");
		baseDao.updateEntity(userInfo);
		return 1;
	}
	/**
	 * 修改密码
	 */
	public int alterPass(String username,String oldPass,String newPass,String code){
		UserInfoEntity userInfo = getUserInfoByValue("username",username);
		String alterPassCode = (String) SessionUtils.getValue(SessionUtils.ALTERPASS_KEY);
		
		if(userInfo == null){
			return -1;
		}
		if(!userInfo.getPassword().equals(oldPass)){
			return -2;
		}
		if(!code.equalsIgnoreCase(alterPassCode)){
			return -3;
		}
		userInfo.setPassword(newPass);
		baseDao.updateEntity(userInfo);
		return 1;
	}
	
	
	
	
	public void setBaseDao(IBaseDao baseDao) {
		this.baseDao = baseDao;
	}
}
